<template>
	<view class="post_index">
		<view class="upload_view">
			<u-upload :fileList="fileList1" :previewFullImage="true" @afterRead="afterRead" @delete="deletePic" name="1"
				multiple :maxCount="3"></u-upload>
		</view>
		<view class="form_container">
			<u-input clearable v-model="params.title" maxlength="30" showWordLimit border="bottom" autoHeight
				placeholder="填写标题会有更多点赞哦~"></u-input>
			<u-textarea autoHeight minHeight="400" maxlength="500" count v-model="params.content" border="bottom"
				placeholder="畅所欲言哦~">
			</u-textarea>
			<view class="btn_con">
				<u-button class="btn" @click="handleSubmit" type="success">发布</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		TOKENNAME,
		HTTP_ADMIN_URL
	} from '@/config/app.js';

	import {
		addCard
	} from '@/api/forum.js'

	import store from '@/store';

	export default {
		onLoad({post}) {
			let data = JSON.parse(decodeURIComponent(post))
			this.params.content = data.content
			this.params.title = data.title
			this.fileList1 = data.images.split(',').map(item=>{
				return {
					url:item
				}
			})
			this.resArr = data.images.split(',')
		},
		data() {
			return {
				imageUpload:false,
				fileList1: [],
				resArr: [],
				params: {
					title: '',
					content: '',
				},
				action: HTTP_ADMIN_URL + '/api/front/upload/blog'
			}
		},
		props: {
			value: String,
			header: {
				type: Object,
				default: () => ({
					// #ifdef MP
					"Content-Type": "multipart/form-data",
					// #endif
					[TOKENNAME]: store.state.app.token,
				})
			},
			name: {
				type: String,
				default: 'multipart'
			},
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
				this.resArr.splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				this.imageUpload = true
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
				this.imageUpload = false
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: `${HTTP_ADMIN_URL}/api/front/user/upload/image?model=maintain&pid=0`, // 
						filePath: url,
						name: 'multipart',
						header: this.header,
						success: (res) => {
							let resData = JSON.parse(res.data)
							this.resArr.push(resData.data.url)
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						},
						fail: (err) => {
							console.log(err);
						}
					});
				})
			},
			handleSubmit() {
				if(this.imageUpload){
					uni.showToast({
						title: '请等待图片上传',
						icon: 'none'
					})
					return
				}
				if (this.params.title === "" || !this.params.title) {
					uni.showToast({
						title: '请输入标题内容',
						icon: 'none'
					})
					return
				}
				let contentCode,titleCode,imagesCode=[]
				uni.getProvider({
					service: 'oauth'
				}).then(providerData=>{
					let provider = providerData[1].provider[0]
					uni.login({
						provider: provider,
					}).then(codeData=>{
						contentCode = codeData[1].code
					})
					uni.login({
						provider: provider,
					}).then(codeData=>{
						titleCode = codeData[1].code
					})
					setTimeout(()=>{
						addCard({
							...this.params,
							'images': this.resArr?.join(','),
							contentCode,titleCode
						}).then(res => {
							if (res.code === 200) {
								uni.showToast({
									title: '发布成功',
								})
								for (let k in this.params) {
									this.params[k] = ""
								}
								this.resArr = []
								this.fileList1 = []
								setTimeout(() => {
									uni.navigateTo({
										url: '/pages/forum/article/article'
									})
								}, 500)
							}
						}).catch(err=>{
							uni.showToast({
								icon: 'none',
								title: err
							})
						})
					},800)
				})
			}
		},
	}
</script>

<style scoped lang="scss">
	.post_index {
		background-color: #fff;
		padding: 40rpx;
		background-size: cover;
		/* 使背景图片固定，覆盖整个屏幕 */
		background-position: center;
		/* 背景图片居中 */
		background-repeat: no-repeat;
		/* 背景图片不重复 */
		width: 100%;
		height: 100vh;
		z-index: -1;
		box-sizing: border-box;

		.upload_view {
			display: flex;
			position: relative;
		}

		.u-button {}

		.form_container {
			margin: 20rpx 0;

			.u-input {
				margin: 20rpx 0;
			}

			.btn_con {
				bottom: 10rpx;
				position: absolute;
				width: 100%;
				left: 0;
				margin-right: -40rpx;
			}


		}
	}
</style>